package com.example.homemate.service.impl.owner;

import com.example.homemate.model.entity.owner.Owner;
import com.example.homemate.model.entity.house.House;
import com.example.homemate.Repository.owner.OwnerRepository;
import com.example.homemate.Repository.house.HouseRepository;
import com.example.homemate.service.owner.OwnerService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OwnerServiceImpl implements OwnerService {

    private final OwnerRepository ownerRepository;
    private final HouseRepository houseRepository;

    @Value("${test.names:陆林轩,袁天罡,蚩梦,唐三,朱竹清,叶修,叶秋,李星云,降臣,姬如雪,张子凡,宁荣荣,戴沐白,千仞雪}")
    private String namesConfig;

    @Value("${test.ages:99,99}")
    private String agesConfig;

    public OwnerServiceImpl(OwnerRepository ownerRepository, HouseRepository houseRepository) {
        this.ownerRepository = ownerRepository;
        this.houseRepository = houseRepository;
        System.out.println("00000222220000000");
    }

    @Override
    @Transactional
    public Page<Owner> getOwners(int page, int size, String sortField, String sortDirection) {
        Sort sort = Sort.by(Sort.Direction.fromString(sortDirection), sortField);
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);
        System.out.println("0000033330000000");
        return ownerRepository.findAll(pageRequest);
    }

    @Override
    @Transactional
    public Owner saveOwner(Owner owner) {
        if (owner.getId() == null) {
            owner.setCreateTime(LocalDateTime.now()); // 统一使用LocalDateTime
        }
        return ownerRepository.save(owner);
    }

    @Override
    @Transactional
    public void deleteOwner(Long id) {
        ownerRepository.deleteById(id);
    }

    @Override
    @Transactional
    public void initTestData() {
        System.out.println("00000444444000000");
        if (ownerRepository.count() > 0) return;

        List<String> names = Arrays.asList(namesConfig.split(","));
        List<Integer> ages = Arrays.stream(agesConfig.split(","))
                .map(Integer::parseInt)
                .toList();
        List<String> genders = Arrays.asList("男", "女");
        System.out.println("00000555555000000");
        for (int i = 0; i < 100; i++) {
            Owner owner = new Owner();
            owner.setName(names.get(ThreadLocalRandom.current().nextInt(names.size()))); // 修正为setName
            owner.setGender(genders.get(ThreadLocalRandom.current().nextInt(genders.size())));
            owner.setAge(ages.get(ThreadLocalRandom.current().nextInt(ages.size())));
            owner.setTel("187" + String.format("%08d", ThreadLocalRandom.current().nextInt(100000000)));
            LocalDate randomDate = LocalDate.now().minusDays(ThreadLocalRandom.current().nextInt(1095));
            owner.setDueDate(randomDate);
            owner.setComments("备注信息" + (ThreadLocalRandom.current().nextInt(10000)));
            ownerRepository.save(owner);
        }
    }

    @Override
    @Transactional
    public Owner updateOwner(Long id, Owner updatedOwner) {
        Owner existingOwner = ownerRepository.findById(id)
                .orElseThrow(() -> new OwnerNotFoundException("业主不存在，ID: " + id));

        existingOwner.setName(updatedOwner.getName()); // 修正为setName
        existingOwner.setGender(updatedOwner.getGender());
        existingOwner.setAge(updatedOwner.getAge());
        existingOwner.setTel(updatedOwner.getTel());
        existingOwner.setDueDate(updatedOwner.getDueDate());
        existingOwner.setComments(updatedOwner.getComments());

        return ownerRepository.save(existingOwner);
    }

    @Override
    @Transactional
    public List<Owner> getAllOwners() {
        return ownerRepository.findAll();
    }

    @Override
    @Transactional
    public Owner getOwnerById(Long id) {
        return ownerRepository.findById(id)
                .orElseThrow(() -> new OwnerNotFoundException("无效业主ID: " + id));
    }

    @Override
    @Transactional
    public Owner bindHouseToOwner(Long ownerId, Long houseId) {
        Owner owner = getOwnerById(ownerId);
        System.out.println("Ownerserviceimpl 实行00002");
        House house = houseRepository.findById(houseId)
                .orElseThrow(() -> new HouseNotFoundException("无效房屋ID: " + houseId));

        if (owner.getHouses() == null) {
            owner.setHouses(new ArrayList<>());
        }

        house.setCheckInTime(LocalDateTime.now());
        owner.getHouses().add(house);

        return ownerRepository.save(owner);
    }

    @Override
    @Transactional
    public List<House> getOwnerHouses(Long ownerId) {
        Owner owner = getOwnerById(ownerId);
        return owner.getHouses();
    }
}

// 自定义异常类
class OwnerNotFoundException extends RuntimeException {
    public OwnerNotFoundException(String message) {
        super(message);
    }
}

class HouseNotFoundException extends RuntimeException {
    public HouseNotFoundException(String message) {
        super(message);
    }
}